<?php


namespace app\api\controller;


use app\common\controller\Api;
use app\common\model\Config;
use app\common\model\PackageOrder;
use app\common\model\StaffClock;
use app\common\model\Tag;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Session;

/**
 * 套餐接口
 */
class Package extends Api
{
    protected $noNeedLogin = ['list'];
    protected $noNeedRight = '*';

    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Package();
    }

    //套餐列表
    public function list()
    {
        $page = $this->request->get('page');
        $limit = $this->request->get('limit',LIMIT);
        $tag_id = $this->request->get('tag_id');
        $condition = $this->request->get('condition',1);
        $switch = $this->request->get('switch');
        $post = $this->request->get('post');
        $state = $this->request->get('state');
        $city = $this->request->get('city');

        $where = [];
        $where['city'] = $city;
        $order = "weigh desc";
        if(!empty($tag_id)) $where['tag_id'] = $tag_id;
        if(!empty($switch)) $where['switch'] = $switch;
        if(!empty($post)) $where['post_id'] = ['neq',''];
        if(!empty($state)) $where['state'] = $state;
        switch ($condition) {
            case '1':
                $order = "createtime desc";
                break;
            case '2':
                $order = "price desc";
                break;
            case '3':

                break;
        }
        $list =  $this->model
            ->with(['staff', 'tag'])
            ->where($where)->order($order)->paginate($limit,false,['page' => $page]);

        foreach ($list as &$row) {
            $row->hidden(['createtime','updatetime','deletetime']);
            if($row->staff) $row->getRelation('staff')->hidden(['mobile', 'address', 'createtime','updatetime','deletetime','no']);
        }
        $result = array("total" => $list->total(), "rows" => $list->items());
        $this->success('返回成功',$result);
    }

    public function detail()
    {
        $id = $this->request->get('id');
        $info =  $this->model->with(['staff', 'tag'])->where(['id' => $id])->find();

        if(!$info) $this->error('参数错误');
        $info->hidden(['createtime','updatetime','deletetime']);
        //如果购买了
        $order = PackageOrder::get([ 'package_id' => $id, 'user_id' => $this->auth->id]);
        $info->is_clock = 0;
        if($order) {
            $info->getRelation('staff')->hidden(['updatetime','deletetime']);
            $info->is_clock = 1;
        }else {
            $info->getRelation('staff')->hidden(['mobile', 'address', 'character', 'createtime','updatetime','deletetime']);
        }
        $info->getRelation('tag')->hidden(['createtime','updatetime','deletetime']);
        $this->success('返回成功',$info);
    }

    public function submit()
    {
        $id = $this->request->get('id');
        $info =  $this->model->with(['staff', 'tag'])->where(['id' => $id])->find();
        if(!$info) $this->error('参数错误');

        //判断用户有没有余额
        $money = $info->price;
        $user = $this->auth->getUser();
        if($user->money < $money) $this->error('当前余额不足，请立即充值','',3);

        $order = PackageOrder::get([ 'package_id' => $id, 'user_id' => $this->auth->id]);

        if(!empty($order)) $this->error('当前套餐已解锁');

        Db::startTrans();
        try {
            $model = new PackageOrder();
            $model->save([
                'code' => mt_rand(1000,9999),
                'package_id' => $id,
                'user_id' => $this->auth->id,
                'staff_id' => $info->staff_id,
                'money' => $money,
                'package_name' => $info->name
            ]);

            $memo = "你购买套餐{$info->name}";

            \app\common\model\Message::setMessage($this->auth->id,$memo,'pages/mine/release?current=1');
            //扣钱
            \app\common\model\User::money(-$money,$user->id,$user->nickname.'购买套餐');
            Db::commit();
        }catch (ValidateException|PDOException|\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success(__('解锁成功'));
    }

    //我的套餐
    public function userlist()
    {
        $page = $this->request->get('page');
        $limit = $this->request->get('limit',LIMIT);
        $state = $this->request->get('state');

        $where = [
            'fa_package_order.user_id' => $this->auth->id,
            'fa_package_order.state' => $state
        ];
        $model = new PackageOrder();
        $list = $model
            ->with(['package','staff'])
            ->where($where)->order('id desc')->paginate($limit,false,['page' => $page]);

        foreach ($list as $row) {
            $row->getRelation('staff')->hidden(['mobile', 'height', 'weight', 'age', 'city', 'no', 'address', 'character','updatetime','deletetime']);
            $tag = Tag::get($row->staff->tag_id);
            $row->tag_name = $tag->name;
        }

        $result = array("total" => $list->total(), "rows" => $list->items());
        $this->success('返回成功',$result);
    }

    //技师套餐
    public function stafflist()
    {
        $page = $this->request->get('page');
        $limit = $this->request->get('limit',LIMIT);
        $state = $this->request->get('state');

        $staff = \app\common\model\Staff::get(['user_id' => $this->auth->id]);
        if(empty($staff)) $this->error('未知技师');
        $where = [
            'fa_package_order.staff_id' =>$staff->id,
            'fa_package_order.state' => $state
        ];
        $model = new PackageOrder();
        $list = $model
            ->with(['package','staff'])
            ->where($where)->order('id desc')->paginate($limit,false,['page' => $page]);

        foreach ($list as $row) {
            $row->getRelation('staff')->hidden(['mobile', 'height', 'weight', 'age', 'city', 'no', 'address', 'character','updatetime','deletetime']);
            $tag = Tag::get($row->staff->tag_id);
            $row->tag_name = $tag->name;
        }

        $result = array("total" => $list->total(), "rows" => $list->items());
        $this->success('返回成功',$result);
    }

    //核销
    public function check()
    {
        $id = $this->request->get('id');
        $code = $this->request->get('code');

        $order = PackageOrder::get(['package_id' => $id, 'code' => $code]);
        if(empty($order)) $this->error('套餐错误');

        $switch = Config::get(['group' => 'example', 'name' => 'package_switch'])->value;
        $ratio = Config::get(['group' => 'example', 'name' => 'package_ratio'])->value;

        $user = \app\common\model\User::get($order->user_id);
        if(!empty($user->p_id) && !empty($switch)) {
            $newpayamount = $order->money * ($ratio / 100);
            \app\common\model\UserIncome::money($newpayamount,$user->p_id,$user->nickname.'购买套餐');
        }

        if($order->save([
            'state' => 1
        ])) {
            $this->success('核销成功');
        }else {
            $this->error('核销失败');
        }
    }
}